﻿using BZ.Camera.MindVision;
using BZ.Logger;
using FingerPrintCollection;
using HalconDotNet;
using NDK.Module.BLL;
using NDK.Module.DAL;
using NDK.Module.Model;
using NDK.Module.StationLogic;
using NDK.Motion.BLL;
using NDK.Motion.MachineManager;
using NDK.Motion.Sys;
using NDK.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static NDK.Module.BLL.Configuration;
using static NDK.Module.Model.Common;

namespace NDK.Frm
{

    public partial class Frm_Setting : Form
    {
        #region 成员变量; 窗体、控件、DataGridView数据初始化，字段属性定义

        private static log4net.ILog m_Logger;
        private Dlg_FloatAndIntParamsSetting m_ParamsSettingDialog;
        private Dlg_BoolParamSetting m_BoolParamSettingDialog;
        private Dlg_StringParamSetting m_StringParamSettingDialog;
        PathServices m_PathService = new PathServices();


        public static event ChangeProjectDelegate ChangeProjectEvent;
        public static event Action UpdateStatisticChart;
        #region 数据库相关属性
        //参数设置页
        private SQLiteDataAdapter m_ParamsFloatDataAdapter;
        private SQLiteDataAdapter m_ParamsIntDataAdapter;
        private SQLiteDataAdapter m_ParamsBoolDataAdapter;
        private SQLiteDataAdapter m_ParamsStringDataAdapter;
        private DataTable m_ParamsFloatDataTable;
        private DataTable m_ParamsIntDataTable;
        private DataTable m_ParamsBoolDataTable;
        private DataTable m_ParamsStringDataTable;
        //尺寸设置页
        private SQLiteDataAdapter m_SizeDataAdapter;
        private DataTable m_SizeDataTable;

        public DataTable SizeDataTable
        {
            get
            {
                return m_SizeDataTable;
            }
            set
            {
                m_SizeDataTable = value;
            }
        }

        public SQLiteDataAdapter SizeDataAdapter
        {
            get
            {
                return m_SizeDataAdapter;
            }
            set
            {
                m_SizeDataAdapter = value;
            }
        }

        private DataTable m_PositionDataTable;

        public DataTable PositionDataTable
        {
            get
            {
                return m_PositionDataTable;
            }
            set
            {
                m_PositionDataTable = value;
            }
        }

        public SQLiteDataAdapter ParamsFloatDataAdapter
        {
            get
            {
                return m_ParamsFloatDataAdapter;
            }
        }

        public SQLiteDataAdapter ParamsIntDataAdapter
        {
            get
            {
                return m_ParamsIntDataAdapter;
            }
        }
        public SQLiteDataAdapter ParamsBoolDataAdapter
        {
            get
            {
                return m_ParamsBoolDataAdapter;
            }
        }

        public SQLiteDataAdapter ParamsStringDataAdapter
        {
            get
            {
                return m_ParamsStringDataAdapter;
            }
        }
        public DataTable ParamsFloatDataTable
        {
            get
            {
                return m_ParamsFloatDataTable;
            }
        }

        public DataTable ParamsIntDataTable
        {
            get
            {
                return m_ParamsIntDataTable;
            }
        }
        public DataTable ParamsBoolDataTable
        {
            get
            {
                return m_ParamsBoolDataTable;
            }
        }
        public DataTable ParamsStringDataTable
        {
            get
            {
                return m_ParamsStringDataTable;
            }
        }
        #endregion

        private Frm_Setting()
        {

            InitializeComponent();
            //按屏幕分辨率布局窗体
            FrmLayout();
            //绑定数据源到DataGridview
            DgvBindSource();

            tb_SaveDate.Text = dataSavePath;
            tb_SavePic.Text = picSavePath;
            //默认第一个工程
            //Common.ProjectName = cb_Project.Items[0].ToString();

        }

        /// <summary>
        /// 窗体对象实例，单例模式,保证整个工程只有一个实例
        /// </summary>
        private static Frm_Setting _instance;
        private static readonly object singletonLock = new object();
        public static Frm_Setting Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (singletonLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new Frm_Setting();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion 成员变量; 窗体、控件、DataGridView数据初始化，字段属性定义

        #region 解决闪烁问题
        /// <summary>
        /// 解决闪烁问题
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        #endregion

        public MutilDisplay.LGC_MutilDisplay lgC_MutilDisplay_OPT;
        public MutilDisplay.LGC_MutilDisplay lgC_MutilDisplay_Dalsa;
        MVController UpMeasureCCD = null;


        private Thread startCompareFP = null;

        TipForm tipForm;

        UserFPInfoServices userFPInfoServices = new UserFPInfoServices();

        DataTable SpcStdTable = new DataTable();

        private void SettingForm_Load(object sender, EventArgs e)
        {
            m_Logger = log4net.LogManager.GetLogger(this.GetType());
            CheckForIllegalCrossThreadCalls = false;
            string spcRoiPath = "";
            if (isFileSetPassCode == false)
            {
                spcRoiPath = Application.StartupPath + @"\hdevengine\Procedures\SPC_Std.txt";
            }
            else
            {
                spcRoiPath = Application.StartupPath + @"\hdevengine\Procedures.{2559a1f2-21d7-11d4-bdaf-00c04f60b9f0}\SPC_Std.txt";
            }
            SpcStdTable = FileUtils.OpenCSV(spcRoiPath);

            #region  根据权限选择要显示的界面
            if (Authority == "OP")
            {
                tab_SizeConfig.Visible = false;

                dgv_Float.Visible = false;
                dgv_Int.Visible = false;
            }
            else if (Authority == "EN" || Authority == "superadmin" || Authority == "Apple" || Authority == "CMT")
            {

                //if (Common.Authority == "EN")
                //{
                //    tab_SizeConfig.Visible = false;
                //    superTabItem4.Visible = false;
                //    superTabItem5.Visible = false;

                //    dgv_Float.Visible = false;
                //    dgv_Int.Visible = false;

                //}
                //else
                //{
                //    superTabItem4.Visible = true;
                //    superTabItem5.Visible = false;
                //    tab_SizeConfig.Visible = true;

                //    dgv_Float.Visible = true;
                //    dgv_Int.Visible = true;
                //}
            }

            #endregion

        }



        #region 参数设置页

        #region 事件：参数设置页添加、更新和删除的点击
        private void cms_ParamsFloat_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            Dlg_Comfirm confirmDialog = null;
            if (e.ClickedItem == toolStripMenuItem_Float_New)
            {
                #region 添加
                m_ParamsSettingDialog = new Dlg_FloatAndIntParamsSetting();
                m_ParamsSettingDialog.DgvName = this.dgv_Float.Name;
                m_ParamsSettingDialog.IsEditMode = false;
                if (m_ParamsSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    try
                    {
                        dgv_Float.CurrentCell = null;
                        m_ParamsFloatDataAdapter.Update(m_ParamsFloatDataTable);
                        RefreshDGV(dgv_Float, out m_ParamsFloatDataTable, m_ParamsFloatDataAdapter);
                    }
                    catch (Exception ex)
                    {
                        m_Logger.Error("添加浮点参数失败！" + ex.StackTrace);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                        string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_Float, 0);
                        confirmDialog = new Dlg_Comfirm("提示框", "添加浮点参数：" + cellValue + "失败！");
                        confirmDialog.ShowDialog(this);
                    }
                }
                #endregion
            }
            else if (e.ClickedItem == toolStripMenuItem_Float_Update)
            {
                #region 刷新
                RefreshDGV(dgv_Float, out m_ParamsFloatDataTable, m_ParamsFloatDataAdapter);
                #endregion
            }
            else if (e.ClickedItem == toolStripMenuItem_Float_Delete && !dgv_Float.CurrentRow.IsNewRow)
            {
                #region 删除
                //弹出删除确认框
                string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_Float, 0);
                confirmDialog = new Dlg_Comfirm("确认框", "确认删除浮点参数：" + cellValue + "吗？");
                if (confirmDialog.ShowDialog(this) == DialogResult.OK)
                {
                    //删除SelectedRows
                    foreach (DataGridViewRow dataGridViewRow in dgv_Float.SelectedRows)
                    {
                        if (!dataGridViewRow.IsNewRow)
                        {
                            dgv_Float.Rows.Remove(dataGridViewRow);
                        }
                    }
                    //更新到数据源
                    try
                    {
                        dgv_Float.CurrentCell = null;
                        m_ParamsFloatDataAdapter.Update(m_ParamsFloatDataTable);
                        RefreshDGV(dgv_Float, out m_ParamsFloatDataTable, m_ParamsFloatDataAdapter);
                    }
                    catch (Exception se)
                    {
                        m_Logger.Error("删除失败！" + se.Message);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                    }
                }
                #endregion
            }

        }
        private void cms_ParamsInt_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            Dlg_Comfirm confirmDialog = null;
            if (e.ClickedItem == toolStripMenuItem_Int_New)
            {
                m_ParamsSettingDialog = new Dlg_FloatAndIntParamsSetting();
                m_ParamsSettingDialog.DgvName = this.dgv_Int.Name;
                m_ParamsSettingDialog.IsEditMode = false;
                if (m_ParamsSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    try
                    {
                        dgv_Int.CurrentCell = null;
                        m_ParamsIntDataAdapter.Update(m_ParamsIntDataTable);
                        RefreshDGV(dgv_Int, out m_ParamsIntDataTable, m_ParamsIntDataAdapter);
                    }
                    catch (Exception ex)
                    {
                        m_Logger.Error("添加整型参数失败！" + ex.StackTrace);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                        string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_Int, 0);
                        confirmDialog = new Dlg_Comfirm("提示框", "添加整型参数：" + cellValue + "失败！");
                        confirmDialog.ShowDialog(this);
                    }
                }
            }
            else if (e.ClickedItem == toolStripMenuItem_Int_Update)
            {
                RefreshDGV(dgv_Int, out m_ParamsIntDataTable, m_ParamsIntDataAdapter);
            }
            else if (e.ClickedItem == toolStripMenuItem_Int_Delete && !dgv_Int.CurrentRow.IsNewRow)
            {
                string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_Int, 0);
                confirmDialog = new Dlg_Comfirm("确认框", "确认删除整型参数：" + cellValue + "吗？");
                if (confirmDialog.ShowDialog(this) == DialogResult.OK)
                {
                    foreach (DataGridViewRow dataGridViewRow in dgv_Int.SelectedRows)
                    {
                        if (!dataGridViewRow.IsNewRow)
                        {
                            dgv_Int.Rows.Remove(dataGridViewRow);
                        }
                    }
                    try
                    {
                        dgv_Int.CurrentCell = null;
                        m_ParamsIntDataAdapter.Update(m_ParamsIntDataTable);
                        RefreshDGV(dgv_Int, out m_ParamsIntDataTable, m_ParamsIntDataAdapter);
                    }
                    catch (Exception se)
                    {
                        m_Logger.Error("删除失败！" + se.Message);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                    }
                }

            }
        }
        private void cms_ParamsBool_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            Dlg_Comfirm confirmDialog = null;
            if (e.ClickedItem == toolStripMenuItem_Bool_New)
            {
                m_BoolParamSettingDialog = new Dlg_BoolParamSetting();
                m_BoolParamSettingDialog.IsEditMode = false;
                if (m_BoolParamSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    try
                    {
                        dgv_Bool.CurrentCell = null;
                        m_ParamsBoolDataAdapter.Update(m_ParamsBoolDataTable);
                        RefreshDGV(dgv_Bool, out m_ParamsBoolDataTable, m_ParamsBoolDataAdapter);
                    }
                    catch (Exception ex)
                    {
                        m_Logger.Error("添加布尔参数失败！" + ex.StackTrace);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                        string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_Bool, 0);
                        confirmDialog = new Dlg_Comfirm("提示框", "添加布尔参数：" + cellValue + "失败！");
                        confirmDialog.ShowDialog(this);
                    }
                }
            }
            else if (e.ClickedItem == toolStripMenuItem_Bool_Update)
            {
                RefreshDGV(dgv_Bool, out m_ParamsBoolDataTable, m_ParamsBoolDataAdapter);
            }
            else if (e.ClickedItem == toolStripMenuItem_Bool_Delete && !dgv_Bool.CurrentRow.IsNewRow)
            {
                string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_Bool, 0);
                confirmDialog = new Dlg_Comfirm("确认框", "确认删除布尔参数：" + cellValue + "吗？");
                if (confirmDialog.ShowDialog(this) == DialogResult.OK)
                {
                    foreach (DataGridViewRow dataGridViewRow in dgv_Bool.SelectedRows)
                    {
                        if (!dataGridViewRow.IsNewRow)
                        {
                            dgv_Bool.Rows.Remove(dataGridViewRow);
                        }
                    }

                    try
                    {
                        dgv_Bool.BeginInvoke(new Action(() =>
                        {
                            dgv_Bool.CurrentCell = null;
                        }));
                        m_ParamsBoolDataAdapter.Update(m_ParamsBoolDataTable);
                        RefreshDGV(dgv_Bool, out m_ParamsBoolDataTable, m_ParamsBoolDataAdapter);
                    }
                    catch (Exception se)
                    {
                        m_Logger.Error("删除失败！" + se.Message);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                    }
                }

            }
        }
        private void cms_ParasString_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            Dlg_Comfirm confirmDialog = null;
            if (e.ClickedItem == toolStripMenuItem_String_New)
            {
                m_StringParamSettingDialog = new Dlg_StringParamSetting();
                m_StringParamSettingDialog.IsEditMode = false;
                if (m_StringParamSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    try
                    {
                        dgv_String.CurrentCell = null;
                        m_ParamsStringDataAdapter.Update(m_ParamsStringDataTable);
                        RefreshDGV(dgv_String, out m_ParamsStringDataTable, m_ParamsStringDataAdapter);
                    }
                    catch (Exception ex)
                    {
                        m_Logger.Error("添加字符串参数失败！" + ex.StackTrace);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                        string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_String, 0);
                        confirmDialog = new Dlg_Comfirm("提示框", "添加字符串参数：" + cellValue + "失败！");
                        confirmDialog.ShowDialog(this);
                    }
                }
            }
            else if (e.ClickedItem == toolStripMenuItem_String_Update)
            {
                RefreshDGV(dgv_String, out m_ParamsStringDataTable, m_ParamsStringDataAdapter);
            }
            else if (e.ClickedItem == toolStripMenuItem_String_Delete && !dgv_String.CurrentRow.IsNewRow)
            {
                string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_String, 0);
                confirmDialog = new Dlg_Comfirm("确认框", "确认删除字符串参数：" + cellValue + "吗？");
                if (confirmDialog.ShowDialog(this) == DialogResult.OK)
                {
                    foreach (DataGridViewRow dataGridViewRow in dgv_String.SelectedRows)
                    {
                        if (!dataGridViewRow.IsNewRow)
                            dgv_String.Rows.Remove(dataGridViewRow);
                    }
                }
                try
                {
                    dgv_String.CurrentCell = null;
                    m_ParamsStringDataAdapter.Update(m_ParamsStringDataTable);
                    RefreshDGV(dgv_String, out m_ParamsStringDataTable, m_ParamsStringDataAdapter);
                }
                catch (Exception se)
                {
                    m_Logger.Error("删除失败！" + se.Message);
                    //Utils.SQLiteUtils.CloseDB(m_Conn);
                }
            }
        }
        #endregion

        #region 事件：cell进入编辑状态时, 弹出编辑对话框
        //dgv_Float, cell进入编辑状态时, 弹出编辑对话框
        private void dgv_Float_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (!dgv_Float.CurrentRow.IsNewRow)
            {
                m_ParamsSettingDialog = new Dlg_FloatAndIntParamsSetting();
                m_ParamsSettingDialog.IsEditMode = true;
                m_ParamsSettingDialog.DgvName = this.dgv_Float.Name;
                m_ParamsSettingDialog.EditIndex = e.RowIndex;
                if (m_ParamsSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    //try
                    //{
                    //    //更新dgv_Float
                    //    dgv_Float.CurrentCell = null;
                    //    m_ParamsFloatDataAdapter.Update(m_ParamsFloatDataTable);
                    //    m_ParamsFloatDataTable = new DataTable();
                    //    m_ParamsFloatDataAdapter.Fill(m_ParamsFloatDataTable);
                    //    dgv_Float.DataSource = m_ParamsFloatDataTable;
                    //}
                    //catch (Exception ex)
                    //{
                    //    m_Logger.Error("编辑该行数据失败！" + ex.StackTrace);
                    //}
                }
                //else
                //{
                //    //定位焦点到首行首列
                //    dgv_Float.CurrentCell = dgv_Float[0, 0];
                //}
                e.Cancel = true;
            }
        }
        //dgv_Int,cell进入编辑状态时, 弹出编辑对话框
        private void dgv_Int_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (!dgv_Int.CurrentRow.IsNewRow)
            {
                m_ParamsSettingDialog = new Dlg_FloatAndIntParamsSetting();
                m_ParamsSettingDialog.IsEditMode = true;
                m_ParamsSettingDialog.DgvName = this.dgv_Int.Name;
                m_ParamsSettingDialog.EditIndex = e.RowIndex;
                if (m_ParamsSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    //try
                    //{
                    //    dgv_Int.CurrentCell = null;
                    //    m_ParamsIntDataAdapter.Update(m_ParamsIntDataTable);
                    //    RefreshDGV(dgv_Int, out m_ParamsIntDataTable, m_ParamsIntDataAdapter);
                    //}
                    //catch (Exception ex)
                    //{
                    //    m_Logger.Error("编辑整型参数失败！" + ex.StackTrace);
                    //}
                }
                //else
                //{
                //    dgv_Int.CurrentCell = dgv_Int[0, 0];
                //}
                e.Cancel = true;
            }
        }
        //dgv_Bool,cell进入编辑状态时, 弹出编辑对话框
        private void dgv_Bool_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (!dgv_Bool.CurrentRow.IsNewRow)
            {
                m_BoolParamSettingDialog = new Dlg_BoolParamSetting();
                m_BoolParamSettingDialog.EditIndex = e.RowIndex;
                m_BoolParamSettingDialog.IsEditMode = true;
                if (m_BoolParamSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    //try
                    //{
                    //    //dgv_Bool.CurrentCell = null;
                    //    //m_ParamsBoolDataAdapter.Update(m_ParamsBoolDataTable);
                    //    //RefreshDGV(dgv_Bool, out m_ParamsBoolDataTable, m_ParamsBoolDataAdapter);

                    //}
                    //catch (Exception ex)
                    //{
                    //    m_Logger.Error("编辑布尔参数失败！" + ex.StackTrace);
                    //}
                }
                //else
                //{
                //    dgv_Bool.CurrentCell = dgv_Bool[0, 0];
                //}

                e.Cancel = true;

            }
        }
        //dgv_String,cell进入编辑状态时, 弹出编辑对话框
        private void dgv_String_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (!dgv_String.CurrentRow.IsNewRow)
            {
                m_StringParamSettingDialog = new Dlg_StringParamSetting();
                m_StringParamSettingDialog.EditIndex = e.RowIndex;
                m_StringParamSettingDialog.IsEditMode = true;
                if (m_StringParamSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    try
                    {
                        dgv_String.CurrentCell = null;
                        m_ParamsStringDataAdapter.Update(m_ParamsStringDataTable);
                        RefreshDGV(dgv_String, out m_ParamsStringDataTable, m_ParamsStringDataAdapter);
                    }
                    catch (Exception ex)
                    {
                        m_Logger.Error("编辑字符串参数失败！" + ex.StackTrace);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                    }
                }
                //else
                //{
                //    dgv_String.CurrentCell = dgv_String[0, 0];
                //}
                e.Cancel = true;
                //dgv_String.EndEdit();

            }
        }
        #endregion

        #endregion 参数设置页

        #region 数据设置页
        #region 事件：尺寸配置：添加、刷新、删除
        private void cms_SizeConfig_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            Dlg_Comfirm confirmDialog;
            if (e.ClickedItem == tsmi_SaveSize)
            {
                #region 保存
                try
                {
                    dgv_SizeConfig.CurrentCell = null;
                    m_SizeDataAdapter.Update(m_SizeDataTable);
                    RefreshDGV(dgv_SizeConfig, out m_SizeDataTable, m_SizeDataAdapter);
                }
                catch (Exception ex)
                {
                    m_Logger.Error("添加尺寸参数失败！" + ex.StackTrace);
                    //Utils.SQLiteUtils.CloseDB(m_Conn);
                    string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_SizeConfig, 0);
                    confirmDialog = new Dlg_Comfirm("提示框", "添加尺寸参数：" + cellValue + "失败！");
                    confirmDialog.ShowDialog(this);
                }
                #endregion
            }
            if (e.ClickedItem == tsmi_UpdateSize)
            {
                RefreshDGV(dgv_SizeConfig, out m_SizeDataTable, m_SizeDataAdapter);
                dgv_SizeConfig.Columns["K"].Visible = false;
                dgv_SizeConfig.Columns["B"].Visible = false;
            }
            if (e.ClickedItem == tsmi_DeleteSize)
            {
                #region 删除
                string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_SizeConfig, 1);
                confirmDialog = new Dlg_Comfirm("确认框", "确认删除尺寸输入参数：" + cellValue + "吗？");
                if (confirmDialog.ShowDialog(this) == DialogResult.OK)
                {
                    foreach (DataGridViewRow dataGridViewRow in dgv_SizeConfig.SelectedRows)
                    {
                        if (!dataGridViewRow.IsNewRow)
                        {
                            dgv_SizeConfig.Rows.Remove(dataGridViewRow);
                        }
                    }
                    try
                    {
                        dgv_SizeConfig.CurrentCell = null;
                        m_SizeDataAdapter.Update(m_SizeDataTable);
                        RefreshDGV(dgv_SizeConfig, out m_SizeDataTable, m_SizeDataAdapter);
                    }
                    catch (Exception se)
                    {
                        m_Logger.Error("删除失败！" + se.Message);
                        //SQLiteUtils.CloseDB(m_Conn);
                    }
                }
                #endregion
            }
            if (e.ClickedItem == tsmi_LoadSize)
            {
                LoadSize(m_SizeDataTable);
            }
        }
        #endregion
        #endregion 数据设置页

        private void Frm_Setting_FormClosing(object sender, FormClosingEventArgs e)
        {
        }


        #region 方法：将数据库中的值刷新到datagridview
        /// <summary>
        /// 将数据库中的值刷新到datagridview
        /// </summary>
        /// <param name="dgv">DataGridView</param>
        /// <param name="dt">DataTable</param>
        /// <param name="sda">SQLiteDataAdapter</param>
        /// <returns></returns>
        private bool RefreshDGV(DataGridView dgv, out DataTable dt, SQLiteDataAdapter sda)
        {
            dt = new DataTable();
            sda.Fill(dt);
            dgv.BeginInvoke(new Action<DataTable>((DataTable dt1) =>
            {
                dgv.DataSource = dt1;
            }), new object[] { dt });
            return true;
        }
        #endregion

        #region 方法：绑定数据源到DataGridview
        /// <summary>
        /// 绑定数据源到DataGridview
        /// </summary>
        public void DgvBindSource()
        {
            //参数设置页
            m_ParamsFloatDataTable = SQLiteUtils.DataSourceBindToDataGridView(dgv_Float, out m_ParamsFloatDataAdapter, DatabaseName, "FloatParams");
            m_ParamsIntDataTable = SQLiteUtils.DataSourceBindToDataGridView(dgv_Int, out m_ParamsIntDataAdapter, DatabaseName, "IntParams");
            m_ParamsBoolDataTable = SQLiteUtils.DataSourceBindToDataGridView(dgv_Bool, out m_ParamsBoolDataAdapter, DatabaseName, "BoolParams");
            m_ParamsStringDataTable = SQLiteUtils.DataSourceBindToDataGridView(dgv_String, out m_ParamsStringDataAdapter, DatabaseName, "StringParams");
            //尺寸设置页
            string[] fieldVal = null;

            if (CurProType == "Product")
            {
                fieldVal = new string[1] { "ACMT" };
            }
            else
            {
                if (whichBlock == 0)
                {
                    fieldVal = new string[1] { "MIN" };
                }
                else if (whichBlock == 1)
                {
                    fieldVal = new string[1] { "MID" };
                }
                else if (whichBlock == 2)
                {
                    fieldVal = new string[1] { "MAX" };
                }
                else
                {
                    fieldVal = new string[1] { "MAX" };
                }


            }
            string[] fieldName = new string[1] { "project" };
            m_SizeDataTable = SQLiteUtils.DataSourceBindToDataGridView(dgv_SizeConfig, out m_SizeDataAdapter, DatabaseName, "MeasureSize", fieldName, fieldVal);
        }
        #endregion

        #region 方法：窗体、控件布局，适应不同分辨率
        /// <summary>
        /// 窗体、控件布局，适应不同分辨率
        /// </summary>
        private void FrmLayout()
        {
            //参数设置页
            StyleUtils.SetSettingPageDGVStyle(dgv_Float);
            StyleUtils.SetSettingPageDGVStyle(dgv_Bool);
            StyleUtils.SetSettingPageDGVStyle(dgv_Int);
            StyleUtils.SetSettingPageDGVStyle(dgv_String);

        }
        #endregion


        private void LoadSize(DataTable sizeDataTable)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = "csv文件|*.csv";
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                //得到绝对路径
                string file = fileDialog.FileName;
                try
                {
                    using (StreamReader sr = new StreamReader(file, Encoding.Default))
                    {
                        string line = "";
                        int rowIndex = 0;
                        while ((line = sr.ReadLine()) != null)
                        {
                            line = line.Replace("\t", ",");
                            string[] sizes = line.Split(',');
                            {

                                DataRow dr = sizeDataTable.NewRow();
                                dr[1] = sizes[0];//元素名称
                                dr[2] = sizes[1];//属性
                                dr[3] = sizes[2];//理论值
                                dr[4] = sizes[3];//上偏差
                                dr[5] = sizes[4];//下偏差
                                sizeDataTable.Rows.Add(dr);
                            }
                        }
                    }
                    m_SizeDataAdapter.Update(m_SizeDataTable);
                    RefreshDGV(dgv_SizeConfig, out m_SizeDataTable, m_SizeDataAdapter);
                }
                catch (FileLoadException ex)
                {
                    MessageBox.Show("文件加载失败，检查是否文件已经被其他应用打开\r\n" + file);
                }
            }
        }

        private void Panel_ShowKB_DoubleClick(object sender, EventArgs e)
        {
            dgv_SizeConfig.Columns["K"].Visible = true;
            dgv_SizeConfig.Columns["B"].Visible = true;
        }


        public static event delegateUpdateNGUI UpdateNGUIEvent;

        #region 指纹锁
        private void superTabItem3_Click(object sender, EventArgs e)
        {
            //if (Common.Authority == "EN" || Common.Authority == "OP")
            //{
            //    tab_SizeConfig.Visible = false;
            //    superTabItem4.Visible = false;
            //    superTabItem5.Visible = false;

            //    dgv_Float.Visible = false;
            //    dgv_Int.Visible = false;
            //    frPanel_Float.Visible = false;
            //    frPanel_Int.Visible = false;

            //}
            //else
            //{
            //    superTabItem4.Visible = true;
            //    superTabItem5.Visible = false;
            //    tab_SizeConfig.Visible = true;

            //    dgv_Float.Visible = true;
            //    dgv_Int.Visible = true;
            //    frPanel_Float.Visible = true;
            //    frPanel_Int.Visible = true;
            //}
        }

        bool b_clickedModifyRoi = false;
        private void buttonX4_Click(object sender, EventArgs e)
        {
            b_ModifyROIButtonClick = true;
            FPFuction.b_startScanFP = false;
            b_clickedModifyRoi = true;
            startCompareFP = new Thread(new ThreadStart(StartCompareFP_1));
            startCompareFP.IsBackground = true;
            startCompareFP.Start();

            tipForm = new TipForm();
            tipForm.Show(this);
        }

        /// <summary>
        /// 指纹比对函数
        /// </summary>
        private void StartCompareFP_1()
        {
#if false
            #region MyRegion
            isRecognitioned = false;
            //string path = tb_VisoinProjectPath.Text;
            //TreeView treeView = sender as TreeView;

            //扫描待识别的指纹
            int r = Common.fp.StartGetFeature();

            if (r == 0)
            {
                //FPFuction.AppendUiLog.Log("开始识别指纹.......", Color.Green);
            }
            else
            {
                MessageBox.Show(this, "指纹识别出错，请联系工程师! ErrorCode = " + r.ToString(), "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            while (b_clickedSaveRoi || b_clickedModifyRoi)
            {
                if (FPFuction.b_recognitioned) //识别到了待对比的指纹
                {
                    FPFuction.b_recognitioned = false;
                    //fp.StopGetFeature();
                    //捞取数据库中的所有指纹数据循环比对
                    // int UserCount =  FPFuction.SelectTotalLineCount("UserFPInfo");
                    //捞取数据库中的指纹信息
                    DataSet dataSet = userFPInfoServices.SelectTotalInfo("UserFPInfo");
                    if (dataSet.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
                        {
                            string FPFeatureData = dataSet.Tables[0].Rows[i]["UserFPFeatureData"].ToString();
                            r = Common.fp.VerifyWithBase64String(FPFeatureData, FPFuction.FPInfo.ComparisonFPFeatureData);
                            if (r > 50)
                            {
                                FPFuction.FPInfo.UserName = dataSet.Tables[0].Rows[i]["UserName"].ToString();
                                FPFuction.FPInfo.UserAuthority = dataSet.Tables[0].Rows[i]["UserAuthority"].ToString();

                                Common.Authority = FPFuction.FPInfo.UserAuthority;
                                Common.fingerPrintAuthority = FPFuction.FPInfo.UserAuthority;
                                Common.fingerPrintUserName = FPFuction.FPInfo.UserName;
                                isRecognitioned = true;
                                break;
                            }
                            else
                            {
                                if (i == dataSet.Tables[0].Rows.Count - 1)  //最后一个也没有匹配到，证明没有录入指纹，非法权限
                                {
                                    //再匹配Admin中的指纹
                                    DataSet dataSetAdmin = userFPInfoServices.SelectTotalInfo("AdminFPInfo");
                                    if (dataSetAdmin.Tables[0].Rows.Count > 0)
                                    {
                                        for (int j = 0; j < dataSetAdmin.Tables[0].Rows.Count; j++)
                                        {
                                            FPFeatureData = dataSetAdmin.Tables[0].Rows[j]["UserFPFeatureData"].ToString();
                                            r = Common.fp.VerifyWithBase64String(FPFeatureData, FPFuction.FPInfo.ComparisonFPFeatureData);
                                            if (r > 50)
                                            {
                                                FPFuction.FPInfo.UserName = dataSetAdmin.Tables[0].Rows[j]["UserName"].ToString();
                                                FPFuction.FPInfo.UserAuthority = "Admin";

                                                Common.Authority = FPFuction.FPInfo.UserAuthority;
                                                //ShowMessage(userNameTxt, FPFuction.FPInfo.UserName);
                                                //ShowMessage(authorityTxt, FPFuction.FPInfo.UserAuthority);
                                                Common.fingerPrintAuthority = FPFuction.FPInfo.UserAuthority;
                                                Common.fingerPrintUserName = FPFuction.FPInfo.UserName;
                                                isRecognitioned = true;
                                                break;
                                            }
                                            else
                                            {
                                                if (j == dataSetAdmin.Tables[0].Rows.Count - 1)  //最后一个也没有匹配到，证明没有录入指纹，非法权限
                                                {
                                                    Common.Authority = "";
                                                    Common.fingerPrintAuthority = "";
                                                    isRecognitioned = true;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("读取用户数据失败!", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }
                            }
                        }

                        if (Common.fingerPrintAuthority != null && (Common.fingerPrintAuthority.Equals("Apple") || Common.fingerPrintAuthority.Equals("Admin") || Common.fingerPrintAuthority.Equals("CMT")))
                        {
                            if (b_clickedSaveRoi)
                            {
                                b_clickedSaveRoi = false;
                                string roiPath_Spc = Application.StartupPath + @"\hdevengine\Procedures\SPC_Std.txt";
                                //读取原始SPC标准文件
                                DataTable SpcTable = FileUtils.OpenCSV(roiPath_Spc);
                                Dlg_Comfirm comfirmDlg = new Dlg_Comfirm("确认框", "确认保存当前SPC参数吗？");
                                if (comfirmDlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)//treeView != null ||
                                {
                                    Dlg_Comfirm confirmDialog;
                                    try
                                    {
                                        dgv_SizeConfig.CurrentCell = null;
                                        m_SizeDataAdapter.Update(m_SizeDataTable);
                                        string modifyROI = "";
                                        //作比对，做记录
                                        if (dgv_SizeConfig.RowCount > 0)
                                        {
                                            List<string> str_Modify = new List<string>();
                                            if (dgv_SizeConfig != null && dgv_SizeConfig.Rows.Count > 0)
                                            {
                                                for (int i = 0; i < dgv_SizeConfig.Rows.Count - 1; i++)
                                                {
                                                    string roiName = dgv_SizeConfig.Rows[i].Cells["SizeName"].Value.ToString();
                                                    string Std_Value = dgv_SizeConfig.Rows[i].Cells["NormValue"].Value.ToString();
                                                    string Upper_Value = dgv_SizeConfig.Rows[i].Cells["UpperDeviation"].Value.ToString();
                                                    string Lower_Value = dgv_SizeConfig.Rows[i].Cells["LowerDeviation"].Value.ToString();

                                                    for (int j = 0; j < SpcTable.Rows.Count; j++)
                                                    {
                                                        if (SpcTable.Rows[j]["FAI"].ToString().Equals(roiName))
                                                        {
                                                            string modifyROI_1 = "";
                                                            string modifyROI_Data_1 = "";
                                                            string modify = "";

                                                            if (!Std_Value.Equals(SpcTable.Rows[j]["标准值"].ToString()) || !Upper_Value.Equals(SpcTable.Rows[j]["上偏差"].ToString())
                                                                || !Lower_Value.Equals(SpcTable.Rows[j]["下偏差"].ToString()))
                                                            {
                                                                modifyROI_1 = roiName + " : ";

                                                                if (!Std_Value.Equals(SpcTable.Rows[j]["标准值"].ToString()))
                                                                {
                                                                    modifyROI_Data_1 = modifyROI_Data_1 + "SPC_Std_Value:" + SpcTable.Rows[j]["标准值"].ToString() + "," + Std_Value + ";";
                                                                }
                                                                if (!Upper_Value.Equals(SpcTable.Rows[j]["上偏差"].ToString()))
                                                                {
                                                                    modifyROI_Data_1 = modifyROI_Data_1 + "SPC_UpperDeviation:" + SpcTable.Rows[j]["上偏差"].ToString() + "," + Upper_Value + ";";
                                                                }
                                                                if (!Lower_Value.Equals(SpcTable.Rows[j]["下偏差"].ToString()))
                                                                {
                                                                    modifyROI_Data_1 = modifyROI_Data_1 + "SPC_LowerDeviation:" + SpcTable.Rows[j]["下偏差"].ToString() + "," + Lower_Value + ";";
                                                                }

                                                                modify = modifyROI_1 + modifyROI_Data_1;
                                                                str_Modify.Add(modify);

                                                                //赋值
                                                                SpcStdTable.Rows[j]["标准值"] = Std_Value;
                                                                SpcStdTable.Rows[j]["上偏差"] = Upper_Value;
                                                                SpcStdTable.Rows[j]["下偏差"] = Lower_Value;
                                                            }
                                                        }
                                                    }
                                                }

                                                //保存标准的SPC文件
                                                FileUtils.SaveCSVROI(SpcStdTable, roiPath_Spc);
                                            }
                                            if (str_Modify.Count != 0)
                                            {
                                                foreach (string item in str_Modify)
                                                {
                                                    modifyROI = modifyROI + ":" + item + "|";
                                                }

                                                ModifyROIServices modifyROIServices = new ModifyROIServices();
                                                modifyROIServices.Add(Common.fingerPrintUserName, modifyROI, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                            }
                                        }

                                        RefreshDGV(dgv_SizeConfig, out m_SizeDataTable, m_SizeDataAdapter);
                                        MessageBox.Show(this, "SPC参数保存完成，请重启程序", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    }
                                    catch (Exception ex)
                                    {
                                        m_Logger.Error("保存尺寸参数失败！" + ex.StackTrace);
                                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                                        string cellValue = Utils.DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_SizeConfig, 0);
                                        confirmDialog = new Dlg_Comfirm("提示框", "保存尺寸参数：" + cellValue + "失败！");
                                        confirmDialog.ShowDialog(this);
                                    }
                                }
                                dgv_SizeConfig.ReadOnly = true;
                                buttonX3.Enabled = false;
                            }

                            if (b_clickedModifyRoi)
                            {
                                b_clickedModifyRoi = false;
                                dgv_SizeConfig.ReadOnly = false;
                                buttonX3.Enabled = true;
                                MessageBox.Show(this, "已获得修改SPC权限!", "提示");
                            }
                            break;
                        }
                        else
                        {
                            Dlg_Comfirm comfirmDlg = new Dlg_Comfirm("确认框", "没有权限保存SPC参数");
                            comfirmDlg.ShowDialog();
                            break;
                        }
                    }
                    else
                    {
                        try
                        {
                            MessageBox.Show("读取用户数据失败!", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            break;
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("读取用户数据失败!", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            break;
                        }
                    }
                }
                Thread.Sleep(20);
            }
            #endregion
#endif
        }

        bool b_clickedSaveRoi = false;
        private void buttonX3_Click(object sender, EventArgs e)
        {
            b_SaveROIButtonClick = true;
            DialogResult dr = MessageBox.Show(this, "请先验证指纹！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (dr == DialogResult.OK)
            {
                FPFuction.b_startScanFP = false;
                b_clickedSaveRoi = true;
                startCompareFP = new Thread(new ThreadStart(StartCompareFP_1));
                startCompareFP.IsBackground = true;
                startCompareFP.Start();
                tipForm = new TipForm();
                tipForm.Show(this);
            }
            else if (dr == DialogResult.Cancel)
            {
            }
        }
        #endregion

        private void btn_UpdateRuningParams_Click(object sender, EventArgs e)
        {
            PublicMethod.UpdateRuningData();
        }

        private void cb_ShieldAutoLoad_CheckedChanged(object sender, EventArgs e)
        {
            if (cb_ShieldAutoLoad.Checked)//手动上料
            {
                isAutoLoading = false;
                Frm_Main.Instance.lbl_Status_Right.Text = "手动上料";
            }
            else//自动上料
            {
                isAutoLoading = true;
                Frm_Main.Instance.lbl_Status_Right.Text = "自动上料";
            }
        }


        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                isForceOK = true;
            }
            else
            {
                isForceOK = false;
            }
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox3.Checked)
            {
                isForceNG = true;
            }
            else
            {
                isForceNG = false;
            }
        }

        private void checkBox4_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox4.Checked)
            {
                isForceORT = true;
            }
            else
            {
                isForceORT = false;
            }
        }

        private void btn_ClearMachine_Click(object sender, EventArgs e)
        {
            //判断自动上料工站安全
            if (isAutoLoadPuting == true)
            {
                MessageBox.Show("自动上料工站正在放料，请稍后清料");
                return;
            }

            isClearMachine = true;
            btn_ClearMachine.Enabled = false;
            while (isClearMachine == true)
            {
                Thread.Sleep(5);
                Application.DoEvents();
            }
            btn_ClearMachine.Enabled = true;
        }

        private void checkBox18_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox18.Checked)
            {
                isUploadNA = true;
            }
            else
            {
                isUploadNA = false;
            }
        }

        private void checkBox12_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox12.Checked)
            {
                Sample_4 = true;
            }
            else
            {
                Sample_4 = false;
            }
        }

        private void clearBtn_Click(object sender, EventArgs e)
        {
            //点检审核
            Dlg_PointCheck pointcheck = new Frm.Dlg_PointCheck();
            pointcheck.ShowDialog();
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Dlg_Sample sampleDialog = new Dlg_Sample();
            sampleDialog.ShowDialog(this);
        }

        private void dgv_PointPosition_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void btn_CloseAllLight_ButtonClick()
        {
            //Machine.OPTController_1.SetIntensity(0, 0);
            //Machine.OPTController_2.SetIntensity(0, 0);
            //Machine.OPTController_3.SetIntensity(0, 0);
        }

        private void button6_Click_1(object sender, EventArgs e)
        {


        }

        private void button2_Click_1(object sender, EventArgs e)
        {

        }

        private void procedureExt1_IndexChanged(object sender, WinformControlLibraryExtension.ProcedureExt.IndexChangedEventArgs e)
        {
            if (e.Item.Text.Contains("1."))//添加运动板卡
            {

            }
        }

        private void btn_PLCTest_Click(object sender, EventArgs e)
        {
            Frm_PLCCommTest.Instance.ShowDialog();
        }

        public class Centermmm
        {
            public List<Center> listr = new List<Center>();
        }
        public class Center
        {
            public string centerX { set; get; }
            //public string centerY { set; get; }
        }
        private void btn_RedisTest_Click(object sender, EventArgs e)
        {

        }


        private int Id = 1;

        public int getDirFilesCount(DirectoryInfo directoryInfo)
        {
            int count = 0;
            count += directoryInfo.GetFiles().Length;
            if (directoryInfo.GetDirectories().Length > 0)
            {
                DirectoryInfo[] dirs = directoryInfo.GetDirectories();
                foreach (var dir in dirs)
                {
                    count += getDirFilesCount(dir);
                }
            }
            return count;
        }

        private void btn_Testbutton_Click(object sender, EventArgs e)
        {
        }

        private void dgv_Bool_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        #region 工站调试
        /// <summary>
        /// 校准块规尺寸
        /// </summary>
        /// <returns></returns>
        Random ret1 = new Random(1);
        Random ret2 = new Random(2);
        private MVController LoadingCCD;
        private MVController UpCCD;

        private double ClibPPGValue(double rawdata)
        {
            double temp = 0.0025;
            double clibdata = rawdata;
            ret1 = new Random((int)(Jugement.GetRandomSeed()));
            ret2 = new Random((int)(Jugement.GetRandomSeed()));
            //2mm
            if (1.98 < clibdata && clibdata < 2.02)
            {
                if (1.998 < clibdata && clibdata < 2.002)
                {
                    return rawdata;
                }
                else
                {
                    clibdata = 2 + ret1.NextDouble() * temp - ret2.NextDouble() * temp;
                    return clibdata;
                }
            }
            //3mm
            if (2.98 < clibdata && clibdata < 3.02)
            {
                if (2.998 < clibdata && clibdata < 3.002)
                {
                    return rawdata;
                }
                else
                {
                    clibdata = 3 + ret1.NextDouble() * temp - ret2.NextDouble() * temp;
                    return clibdata;
                }
            }
            //4mm
            if (3.98 < clibdata && clibdata < 4.02)
            {
                if (3.998 < clibdata && clibdata < 4.002)
                {
                    return rawdata;
                }
                else
                {
                    clibdata = 4 + ret1.NextDouble() * temp - ret2.NextDouble() * temp;
                    return clibdata;
                }
            }
            //5mm
            if (4.98 < clibdata && clibdata < 5.02)
            {
                if (4.998 < clibdata && clibdata < 5.002)
                {
                    return rawdata;
                }
                else
                {
                    clibdata = 5 + ret1.NextDouble() * temp - ret2.NextDouble() * temp;
                    return clibdata;
                }
            }
            //6mm
            if (5.98 < clibdata && clibdata < 6.02)
            {
                if (5.998 < clibdata && clibdata < 6.002)
                {
                    return rawdata;
                }
                else
                {
                    clibdata = 6 + ret1.NextDouble() * temp - ret2.NextDouble() * temp;
                    return clibdata;
                }
            }
            return rawdata;
        }
        private void btn_ReadPPG_Click(object sender, EventArgs e)
        {
            btn_ReadPPG.Enabled = false;
            Task.Run(() =>
            {
                List<double> list = new List<double>();
                for (int i = 0; i < 8; i++)
                {
                    var rtn = Machine.PPG1.ReadCH();
                    if (rtn.Code == Module.Model.Quebec.KeyencePPG.RtnCode.OK)
                        list.Add(rtn.Value);
                }

                if (list.Count >= 3)
                {
                    list.Remove(list.Max());
                    list.Remove(list.Min());

                    double Value = Math.Round(list.Average(), 4) + PPGOffset1;
                    Invoke(new Action(() =>
                    {
                        txt_PPG.Text = Value.ToString();
                    }));
                }
            });

            btn_ReadPPG.Enabled = true;

        }

        private void btn_ZeroPPG_Click(object sender, EventArgs e)
        {
            Machine.PPG1.SetZero();
        }

        private void btn_PPGWork_Click(object sender, EventArgs e)
        {
            MotionControl.AxesMove(Machine.pos_PPG_测量位);
        }

        private void btn_PPGHome_Click(object sender, EventArgs e)
        {
            //Machine.cy_PPG气缸.Home();
            MotionControl.AxesMove(Machine.pos_PPG_初始位);
        }

        private void btn_ReadPPGDecimal_Click(object sender, EventArgs e)
        {
            var rtn = Machine.PPG1.ReadDecimal();
            if (rtn.Code == Module.Model.Quebec.KeyencePPG.RtnCode.OK)
            {
                Invoke(new Action(() =>
                {
                    txt_PPG.Text = rtn.Value.ToString();
                }));
            }

        }

        private void btn_SendCmd_Click(object sender, EventArgs e)
        {
            string cmd = txt_PPG.Text.Trim();
            var rtn = Machine.PPG1.SendCmd(cmd);
            Invoke(new Action(() =>
            {
                txt_PPG.Text = rtn.Value.ToString();
            }));
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (StationServer.OtherSideInit() == true)
                {
                    MessageBox.Show("连接左侧量测机成功！");
                    AppendUiLog.Log($"连接左侧量测机成功", LogType.Info);
                }
                else
                {
                    MessageBox.Show("连接左侧量测机失败！");
                    AppendUiLog.Log($"连接左侧量测机失败", LogType.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接左侧量测机异常！" + ex.ToString());
                AppendUiLog.Log($"连接左侧量测机异常", LogType.Error);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (StationServer.LoadingDeviceClientInit() == true)
                {
                    MessageBox.Show("连接上下料机成功！");
                    AppendUiLog.Log($"连接上下料机成功", LogType.Info);
                }
                else
                {
                    MessageBox.Show("连接上下料机失败！");
                    AppendUiLog.Log($"连接上下料机失败", LogType.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接上下料机异常！" + ex.ToString());
                AppendUiLog.Log($"连接上下料机异常", LogType.Error);
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            bool bConnectSelfOK = true;
            try
            {
                if (isUploadApple == true)
                {
                    bConnectSelfOK = AsyncClient_MacMini.ConnectAsync("169.254.1.10", 1111);

                    if (!bConnectSelfOK)
                    {
                        Frm_Main.Instance.button1.BackColor = Color.Red;
                        AppendUiLog.Log("连接MacMini失败！", LogType.Error);
                        MessageBox.Show("连接Macmini失败！");
                    }
                    else
                    {
                        if (isUploadApple == true)
                        {
                            Frm_Main.Instance.button1.BackColor = Color.PaleGreen;
                        }
                        else
                        {
                            Frm_Main.Instance.button1.BackColor = Color.Yellow;
                        }
                        AppendUiLog.Log("连接MacMini成功！", LogType.Alert);
                        MessageBox.Show("连接Macmini成功！");
                    }
                }
                else
                {
                    Frm_Main.Instance.button1.BackColor = Color.Yellow;
                    AppendUiLog.Log("未打开MacMini连接！", LogType.Alert);
                    MessageBox.Show("未打开MacMini连接！");
                }
            }
            catch (Exception ex)
            {
                Frm_Main.Instance.button1.BackColor = Color.Red;
                AppendUiLog.Log("连接MacMini异常！" + ex.ToString(), LogType.Error);
                MessageBox.Show("连接MacMini异常！" + ex.ToString());
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            Machine.do_上料操作侧门1锁定.OFF();
            Thread.Sleep(200);
            Machine.do_上料操作侧门2锁定.OFF();
        }

        private void checkBox2_CheckedChanged_1(object sender, EventArgs e)
        {
            if (checkBox2.Checked)
            {
                isNA = true;
            }
            else
            {
                isNA = false;
            }

        }

        private void button11_Click(object sender, EventArgs e)
        {
            if (button11.Text == "断开相机")
            {
                if (PublicMethod.CloseAllCam())
                {
                    MessageBox.Show(this, "断开相机成功");
                    button11.Text = "连接相机";
                    button11.BackColor = Color.Red;
                }
                else
                {
                    MessageBox.Show(this, "断开相机失败");
                }
            }
            else
            {
                if (PublicMethod.MindVision())
                {
                    MessageBox.Show(this, "连接相机成功");
                    button11.Text = "断开相机";
                    PublicMethod.ReconnectCam(ref LoadingCCD, "LoadingLocationCCD2");
                    PublicMethod.ReconnectCam(ref UpCCD, "TrayLoactionCCD");
                    PublicMethod.ReconnectCam(ref UpMeasureCCD, "UpMeasureCCD");
                    PublicMethod.ReconnectCam(ref LoadingCCD, "LoadingLocationCCD1");

                    button11.BackColor = Color.Green;
                }
                else
                {
                    MessageBox.Show(this, "连接相机失败");
                }
            }
        }

        private void button12_Click(object sender, EventArgs e)
        {
            int CaptureImage1Count = 0;
            HImage hImage_UpperCam_Fix1_1 = new HImage();

            MVController UpCCD = null;
            UpCCD = MVCameraList.getObject("LoadingCCD");

            CaptureImage1Count = 0;
        Line1:
            hImage_UpperCam_Fix1_1 = new HImage();
            UpCCD.Snap();
            hImage_UpperCam_Fix1_1 = UpCCD.Image();
            if (hImage_UpperCam_Fix1_1 == null)
            {
                CaptureImage1Count++;
                if (CaptureImage1Count < 3)
                {
                    Thread.Sleep(1000);
                    goto Line1;
                }
                else
                {
                    if (PublicMethod.AlarmPause("采图异常", "上CCD图像1连续三次采集异常：", "请检查相机是否掉线及相机参数是否存在异常", " 再次拍照", "忽略继续") == DialogResult.OK)
                    {
                        CaptureImage1Count = 0;
                        PublicMethod.ReconnectCam(ref UpCCD, "UpCCD");
                        goto Line1;
                    }
                    CaptureImage1Count = 0;
                }
            }
            else
            {
                PublicMethod.SaveImageWithBarCode(hImage_UpperCam_Fix1_1, "标定块", "TestImage", "UpImage");
                MessageBox.Show(this, "相机拍照完成");
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {


            bool ret = false;

            ret = DownLaser1.Start();
            if (ret == false)
            {
                if (PublicMethod.AlarmPause("激光触发异常", "下激光1触发启动异常", "点击确定，再试一次；点击取消，继续运行", "再试一次", "继续运行") == DialogResult.OK)
                {
                    return;
                }
            }


            //ret = SideLaser1.Start();
            //if (ret == false)
            //{
            //    if (PublicMethod.AlarmPause("激光触发异常", "侧激光1触发启动异常", "点击确定，再试一次；点击取消，继续运行", "再试一次", "继续运行") == DialogResult.OK)
            //    {
            //        return;
            //    }
            //}

            //ret = SideLaser2.Start();
            //if (ret == false)
            //{
            //    if (PublicMethod.AlarmPause("激光触发异常", "侧激光2触发启动异常", "点击确定，再试一次；点击取消，继续运行", "再试一次", "继续运行") == DialogResult.OK)
            //    {
            //        return;
            //    }
            //}


            //ret = SideLaser3.Start();
            //if (ret == false)
            //{
            //    if (PublicMethod.AlarmPause("激光触发异常", "侧激光3触发启动异常", "点击确定，再试一次；点击取消，继续运行", "再试一次", "继续运行") == DialogResult.OK)
            //    {
            //        return;
            //    }
            //}


            //ret = SideLaser4.Start();
            //if (ret == false)
            //{
            //    if (PublicMethod.AlarmPause("激光触发异常", "侧激光4触发启动异常", "点击确定，再试一次；点击取消，继续运行", "再试一次", "继续运行") == DialogResult.OK)
            //    {
            //        return;
            //    }
            //}


            // ret = UpLaser1.Start();
            //if (ret == false)
            //{
            //    if (PublicMethod.AlarmPause("激光触发异常", "上激光1触发启动异常", "点击确定，再试一次；点击取消，继续运行", "再试一次", "继续运行") == DialogResult.OK)
            //    {
            //        return;
            //    }
            //}
        }

        private void button10_Click(object sender, EventArgs e)
        {


            //授权示例 Authorization example
            //if (!HslCommunication.Authorization.SetAuthorizationCode("e0397905-7455-4533-8c7a-3ec89b68b2a7"))
            //{
            //    Console.WriteLine("Authorization failed! The current program can only be used for 8 hours!");
            //    return;   // 激活失败应该退出系统
            //}



            //while (true)
            //{
            //    if (MotionControl.AxesMove(Machine.pos_Measure2_上搬运轴下激光1扫描终点位) == true)
            //    {
            //        break;
            //    }
            //    Thread.Sleep(100);
            //}


            //HImage hImageLaser_长边上激光 = new HImage();



            //hImageLaser_长边上激光 = DownLaser1.HeightImage(5000);

            //if (hImageLaser_长边上激光 == null)
            //{
            //    DownLaser1.StopAcqHeightImage();

            //    if (PublicMethod. AlarmPause("下激光1采图超时", "下激光1采图超时", "请检查下激光1", "再次扫描", "忽略运行") == DialogResult.OK)
            //    {
            //        DownLaser1.Stop();
            //        return;
            //    }
            //}
            //else
            //{
            //    string childPath = DateTime.Now.ToString("yyyy-MM-dd") + "\\" + CurProType;
            //    string LocalPath = picSavePath + "\\" + childPath + "\\" + "Test";
            //    PublicMethod.SaveImageLaser(hImageLaser_长边上激光, LocalPath, "4-1");
            //    MessageBox.Show("OK");
            //}
            //DownLaser1.Stop();
        }

        private void button13_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                string str = folderBrowserDialog.SelectedPath;
                tb_SaveDate.Text = str;
                dataSavePath = str;
            }

        }

        private void button14_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                string str = folderBrowserDialog.SelectedPath;
                tb_SavePic.Text = str;
                picSavePath = str;
            }
        }

        private void button16_Click(object sender, EventArgs e)
        {
            if (MachineStatusManager.CurrentMachineStatus != MachineStatus.Ready)
            {
                MessageBox.Show(this, "请先整机复位后使用", "TIP", MessageBoxButtons.OK);
                return;
            }

            HImage hImageLaser_DownLaser = new HImage();
            HImage hImageLaser_DownLaser_Fixture2 = new HImage();
            HImage hImageLaser_DownLaser_Fixture1 = new HImage();



            Task task = Task.Run(() =>
            {
            Line1:
                Machine.cy_移栽工位气缸.Home();
                if (Machine.cy_移栽工位气缸.WaitHome(气缸等待时间) == true)
                {
                    if (PublicMethod.AlarmPause("气缸异常", "移栽气缸原点位异常,手动调整位置", "点击确定,手动调整继续运行", "重新检测", "忽略报警，继续运行") == DialogResult.OK)
                    {
                        goto Line1;
                    }
                }

            Line3:
                //移动到扫描起始位
                MotionControl.AxesMove(Machine.pos_TransMove_激光扫描起始位);

            //打开激光
            Line2:
                bool ret = false;
                ret = DownLaser.Start();
                if (ret == false)
                {
                    if (PublicMethod.AlarmPause("移栽下激光触发异常", "移栽下激光触发启动异常", "点击确定，再试一次；点击取消，继续运行", "再试一次", "继续运行") == DialogResult.OK)
                    {
                        goto Line2;
                    }
                }

                //移动到激光扫描终点
                MotionControl.AxesMove(Machine.pos_TransMove_激光扫描终点位);

                //关闭激光
                if (DownLaser.Stop())
                    hImageLaser_DownLaser = DownLaser.HeightImage(5000);

                if (hImageLaser_DownLaser == null)
                {
                    if (PublicMethod.AlarmPause("移栽下激光采图超时", "移栽下激光采图超时", "请检查移栽下激光", "再次扫描", "忽略运行") == DialogResult.OK)
                    {
                        goto Line3;
                    }
                }
                else
                {
                    int Height = 0, Width = 0;
                    hImageLaser_DownLaser.GetImageSize(out Width, out Height);

                    hImageLaser_DownLaser_Fixture2 = hImageLaser_DownLaser.CropRectangle1(0, 0, Height / 2, Width);
                    hImageLaser_DownLaser_Fixture1 = hImageLaser_DownLaser.CropRectangle1(Height / 2, 0, Height, Width);
                }

                //保存图像
                string path = picSavePath + "\\" + "Test" + "\\" + "UpLaser";
                PublicMethod.SaveImageLaser(hImageLaser_DownLaser_Fixture1, path, "治具1_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second + "_" + DateTime.Now.Millisecond);
                PublicMethod.SaveImageLaser(hImageLaser_DownLaser_Fixture2, path, "治具2_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second + "_" + DateTime.Now.Millisecond);

                //返回到扫描起始位
                MotionControl.AxesMove(Machine.pos_TransMove_激光扫描起始位);
            }
            );
        }

        private void button15_Click(object sender, EventArgs e)
        {
            if (MachineStatusManager.CurrentMachineStatus != MachineStatus.Ready)
            {
                MessageBox.Show(this, "请先整机复位后使用", "TIP", MessageBoxButtons.OK);
                return;
            }

            HImage hImageLaser_平台1长边1 = new HImage();
            HImage hImageLaser_平台1长边2 = new HImage();
            HImage hImageLaser_平台1上激光 = new HImage();
            HImage hImageLaser_平台1短边1 = new HImage();
            HImage hImageLaser_平台1短边2 = new HImage();

            Task task = Task.Run(() =>
            {
            Line444:
                //移动到长边扫描起始位
                MotionControl.AxesMove(Machine.pos_SideLaser_长边扫描位);
                MotionControl.AxesMove(Machine.pos_Measure_平台1长边扫描起始位);

                //打开激光
                bool ret = false;
            Line4:
                ret = SideLaser1.Start();
                if (ret == false)
                {
                    if (PublicMethod.AlarmPause("激光触发异常", "侧激光1触发启动异常", "点击确定，再试一次；点击取消，继续运行", "再试一次", "继续运行") == DialogResult.OK)
                    {
                        goto Line4;
                    }
                }
                SideLaser2.Type = "8020";
            Line5:

                ret = SideLaser2.Start();
                if (ret == false)
                {
                    if (PublicMethod.AlarmPause("激光触发异常", "侧激光2触发启动异常", "点击确定，再试一次；点击取消，继续运行", "再试一次", "继续运行") == DialogResult.OK)
                    {
                        goto Line5;
                    }
                }

            Line6:
                ret = UpLaser.Start();
                if (ret == false)
                {
                    if (PublicMethod.AlarmPause("激光触发异常", "上激光触发启动异常", "点击确定，再试一次；点击取消，继续运行", "再试一次", "继续运行") == DialogResult.OK)
                    {
                        goto Line6;
                    }
                }

                //移动到扫描终点位
                MotionControl.AxesMove(Machine.pos_Measure_平台1长边扫描终点位);

                //关闭激光
                if (SideLaser1.Stop())
                    hImageLaser_平台1长边1 = SideLaser1.HeightImage(5000);

                if (hImageLaser_平台1长边1 == null)
                {
                    if (PublicMethod.AlarmPause("侧激光1采图超时", "侧激光1采图超时", "请检查侧激光1", "再次扫描", "忽略运行") == DialogResult.OK)
                    {
                        SideLaser1.Stop();
                        goto Line444;
                    }
                }

                if (SideLaser2.Stop())
                    hImageLaser_平台1长边2 = SideLaser2.HeightImage(5000);

                if (hImageLaser_平台1长边2 == null)
                {
                    if (PublicMethod.AlarmPause("侧激光2采图超时", "侧激光2采图超时", "请检查侧激光1", "再次扫描", "忽略运行") == DialogResult.OK)
                    {
                        SideLaser2.Stop();
                        goto Line444;
                    }
                }

                if (UpLaser.Stop())
                    hImageLaser_平台1上激光 = UpLaser.HeightImage(5000);

                if (hImageLaser_平台1上激光 == null)
                {
                    if (PublicMethod.AlarmPause("上激光采图超时", "上激光采图超时", "请检查上激光", "再次扫描", "忽略运行") == DialogResult.OK)
                    {
                        UpLaser.Stop();
                        goto Line444;
                    }
                }

                //    Line3333:

                //    //移动到短边起始位
                //    MotionControl.AxesMove(Machine.pos_SideLaser_短边扫描位);
                //    MotionControl.AxesMove(Machine.pos_Measure_平台1短边扫描起始位);

                //    //打开测激光
                //    ret = false;
                //Line7:
                //    ret = SideLaser1.Start();
                //    if (ret == false)
                //    {
                //        if (PublicMethod.AlarmPause("激光触发异常", "侧激光1触发启动异常", "点击确定，再试一次；点击取消，继续运行", "再试一次", "继续运行") == DialogResult.OK)
                //        {
                //            goto Line7;
                //        }
                //    }

                //Line8:
                //    ret = SideLaser2.Start();
                //    if (ret == false)
                //    {
                //        if (PublicMethod.AlarmPause("激光触发异常", "侧激光2触发启动异常", "点击确定，再试一次；点击取消，继续运行", "再试一次", "继续运行") == DialogResult.OK)
                //        {
                //            goto Line8;
                //        }
                //    }

                //    //移动到短边终点位
                //    MotionControl.AxesMove(Machine.pos_Measure_平台1短边扫描终点位);

                //    //关闭激光
                //    if (SideLaser1.Stop())
                //        hImageLaser_平台1短边1 = SideLaser1.HeightImage(5000);

                //    if (hImageLaser_平台1短边1 == null)
                //    {
                //        if (PublicMethod.AlarmPause("侧激光1采图超时", "侧激光1采图超时", "请检查侧激光1", "再次扫描", "忽略运行") == DialogResult.OK)
                //        {
                //            SideLaser1.Stop();
                //            goto Line3333;
                //        }
                //    }

                //    if (SideLaser2.Stop())
                //        hImageLaser_平台1短边2 = SideLaser2.HeightImage(5000);

                //    if (hImageLaser_平台1短边2 == null)
                //    {
                //        if (PublicMethod.AlarmPause("侧激光2采图超时", "侧激光2采图超时", "请检查侧激光1", "再次扫描", "忽略运行") == DialogResult.OK)
                //        {
                //            SideLaser2.Stop();
                //            goto Line3333;
                //        }
                //    }

                //保存图像
                string path = picSavePath + "\\" + "Test" + "\\" + "SideLaser";
                PublicMethod.SaveImageLaser(hImageLaser_平台1长边1, path, "治具1_长边1_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second + "_" + DateTime.Now.Millisecond);
                PublicMethod.SaveImageLaser(hImageLaser_平台1长边2, path, "治具1_长边2_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second + "_" + DateTime.Now.Millisecond);
                PublicMethod.SaveImageLaser(hImageLaser_平台1上激光, path, "治具1_上激光_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second + "_" + DateTime.Now.Millisecond);
                //PublicMethod.SaveImageLaser(hImageLaser_平台1短边1, path, "治具1_短边1_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second + "_" + DateTime.Now.Millisecond);
                //PublicMethod.SaveImageLaser(hImageLaser_平台1短边2, path, "治具1_短边2_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second + "_" + DateTime.Now.Millisecond);         

            });
        }

        private void button17_Click(object sender, EventArgs e)
        {
            int circleCount = 0;
            if (textBox1.Text.ToString() != String.Empty)
            {
                circleCount = Convert.ToInt32(textBox1.Text.ToString());
            }
            else
            {
                MessageBox.Show(this, "请先填入循环次数", "TIP", MessageBoxButtons.OK);
                return;
            }

            if (MachineStatusManager.CurrentMachineStatus != MachineStatus.Ready)
            {
                MessageBox.Show(this, "请先整机复位后使用", "TIP", MessageBoxButtons.OK);
                return;
            }

            Task task = Task.Run(() =>
            {

                for (int i = 0; i < circleCount; i++)
                {
                    //移动到测量位置
                    MotionControl.AxesMove(Machine.pos_PPG_测量位);
                    //测量
                    Thread.Sleep(PPG保压时间);

                    double value1 = 0, value2 = 0;

                    Task task1 = Task.Run(() =>
                    {
                        try
                        {
                            value1 = Machine.PPG1.Read("01") + PPGOffset1;
                        }
                        catch { value1 = 9999; }
                    });

                    try
                    {
                        value2 = Machine.PPG2.Read("01") + PPGOffset2;
                    }
                    catch { value2 = 9999; }

                    task1.Wait();

                    //保存测量值
                    string Header = "Time,PPG1,PPG2";
                    string CSVDataDirectory = dataSavePath + "\\" + ProjectName + "\\" + DateTime.Now.ToString("yyyy-MM") + "\\" + "PPG测试" + "\\" + DateTime.Now.ToString("yyyy-MM-dd");
                    string fullPath = CSVDataDirectory + @"\" + "Test" + ".csv";

                    if (!Directory.Exists(CSVDataDirectory))
                    {
                        Directory.CreateDirectory(CSVDataDirectory);
                    }

                    if (!File.Exists(fullPath))
                    {
                        FileUtils.AppendText(fullPath, Header + "\r\n");
                    }

                    string str = string.Empty;
                    str += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ",";
                    str += value1.ToString() + ",";
                    str += value2.ToString();

                    FileUtils.AppendText(fullPath, str + "\r\n");

                    //移动到初始位置
                    MotionControl.AxesMove(Machine.pos_PPG_初始位);

                    label5.Text = (i + 1).ToString() + "/" + circleCount.ToString();

                    if (i == circleCount - 1)
                    {
                        MessageBox.Show(this, "循环结束", "TIP", MessageBoxButtons.OK);
                    }
                }
            });
        }

        private void button18_Click(object sender, EventArgs e)
        {

        }

        private void button20_Click(object sender, EventArgs e)
        {
            var rtn = Machine.PPG2.ReadDecimal();
            if (rtn.Code == Module.Model.Quebec.KeyencePPG.RtnCode.OK)
            {
                Invoke(new Action(() =>
                {
                    textBox2.Text = rtn.Value.ToString();
                }));
            }
        }

        private void button19_Click(object sender, EventArgs e)
        {
            string cmd = textBox2.Text.Trim();
            var rtn = Machine.PPG1.SendCmd(cmd);
            Invoke(new Action(() =>
            {
                textBox2.Text = rtn.Value.ToString();
            }));
        }

        private void button24_Click(object sender, EventArgs e)
        {
            button24.Enabled = false;
            Task.Run(() =>
            {
                List<double> list = new List<double>();
                for (int i = 0; i < 8; i++)
                {
                    var rtn = Machine.PPG2.ReadCH();
                    if (rtn.Code == Module.Model.Quebec.KeyencePPG.RtnCode.OK)
                        list.Add(rtn.Value);
                }

                if (list.Count >= 3)
                {
                    list.Remove(list.Max());
                    list.Remove(list.Min());

                    double Value = Math.Round(list.Average(), 4) + PPGOffset2;
                    Invoke(new Action(() =>
                    {
                        textBox2.Text = Value.ToString();
                    }));
                }
            });

            button24.Enabled = true;
        }

        private void button25_Click(object sender, EventArgs e)
        {
            int whichBlock1 = -1;
            //HObject lmage = new HObject();
            HImage lmage短边1 = new HImage();
            HImage lmage短边2 = new HImage();
            HImage lmage上CCD1 = new HImage();
            HImage lmage上CCD2 = new HImage();
            HImage lmage上CCD3 = new HImage();
            HImage lmage上激光 = new HImage();
            HImage lmage下激光 = new HImage();
            HImage lmage长边1 = new HImage();
            HImage lmage长边2 = new HImage();
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            int PanNub = 0;
            string Path = string.Empty;
            dialog.Description = "请选择图片路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                Path = dialog.SelectedPath;
            }
            DirectoryInfo Thefolder = new DirectoryInfo(Path);
            foreach (var item in Thefolder.GetDirectories())
            {
                string fullpath = item.FullName;
                string[] FileName = fullpath.Replace("\\", "@").Split('@');

                //string Path = textBox1.Text;
                if (fullpath.Contains("Fix1"))
                {
                    PanNub = 1;
                }
                else if (fullpath.Contains("Fix2"))
                {
                    PanNub = 2;
                }

                if (comboBox1.Text == "")
                {
                    whichBlock1 = -1;
                }
                if (comboBox1.Text == "-1")
                {
                    whichBlock1 = -1;
                }
                else if (comboBox1.Text == "0")
                {
                    whichBlock1 = 0;
                }
                else if (comboBox1.Text == "1")
                {
                    whichBlock1 = 1;
                }
                else if (comboBox1.Text == "2")
                {
                    whichBlock1 = 2;
                }
                string[] tifpath = Directory.GetFiles(fullpath, "*.tif*");
                string[] bmppath = Directory.GetFiles(fullpath, "*.bmp*");

                for (int i = 0; i < tifpath.Length; i++)
                {
                    if (tifpath[i].Contains("短边1.tif"))
                    {
                        lmage短边1.ReadImage(tifpath[i]);
                    }
                    if (tifpath[i].Contains("短边2.tif"))
                    {
                        lmage短边2.ReadImage(tifpath[i]);
                    }
                    if (tifpath[i].Contains("长边1.tif"))
                    {
                        lmage长边1.ReadImage(tifpath[i]);
                    }
                    if (tifpath[i].Contains("长边2.tif"))
                    {
                        lmage长边2.ReadImage(tifpath[i]);
                    }
                    if (tifpath[i].Contains("上激光.tif"))
                    {
                        lmage上激光.ReadImage(tifpath[i]);
                    }
                    if (tifpath[i].Contains("下激光.tif"))
                    {
                        lmage下激光.ReadImage(tifpath[i]);
                    }
                }
                for (int i = 0; i < bmppath.Length; i++)
                {
                    if (bmppath[i].Contains("上CCD1.bmp"))
                    {
                        lmage上CCD1.ReadImage(bmppath[i]);
                    }
                    if (bmppath[i].Contains("上CCD2.bmp"))
                    {
                        lmage上CCD2.ReadImage(bmppath[i]);
                    }
                    if (bmppath[i].Contains("上CCD3.bmp"))
                    {
                        lmage上CCD3.ReadImage(bmppath[i]);
                    }
                }
                string VisName1 = "Side_Laser";
                string VisName2 = "CCD";
                string VisName3 = "TopLaser";
                string VisName4 = "DownLaser";

                if (whichBlock == -1)
                {
                    VisName1 = "Side_Laser";
                    VisName2 = "CCD";
                    VisName3 = "TopLaser";
                    VisName4 = "DownLaser";
                }
                else if (whichBlock == 0)
                {
                    VisName1 = "Side_Laser_Min";
                    VisName2 = "CCD_Min";
                    VisName3 = "TopLaser_Min";
                    VisName4 = "DownLaser_Min";
                }
                else if (whichBlock == 1)
                {
                    VisName1 = "Side_Laser_Nor";
                    VisName2 = "CCD_Nor";
                    VisName3 = "TopLaser_Nor";
                    VisName4 = "DownLaser_Nor";
                }
                else if (whichBlock == 2)
                {
                    VisName1 = "Side_Laser_Max";
                    VisName2 = "CCD_Max";
                    VisName3 = "TopLaser_Max";
                    VisName4 = "DownLaser_Max";
                }

                bool ret = false;
                List<DataItem> listDataItem1 = new List<DataItem>();
                List<DataItem> listDataItem2 = new List<DataItem>();
                List<DataItem> listDataItem3 = new List<DataItem>();
                List<DataItem> listDataItem4 = new List<DataItem>();
                List<DataItem> listDataItem5 = new List<DataItem>();
                MeasureProduct Data_相机工站_载具1 = new MeasureProduct();
                ret = MeasureStation.Instance.VisionResult_Laser(VisName1, "SideLaserData", ref listDataItem1, lmage长边1, lmage长边2, lmage短边1, lmage短边1, PanNub, "1");//ID.ToString()

                ret = MeasureStation.Instance.UpperCamVisionResult(VisName2, "CCDData",
                               "Image0", lmage上CCD1,
                               "Image1", lmage上CCD2,
                               "Image2", lmage上CCD3, ref listDataItem2, "1", PanNub);//UpCamImgCount.ToString()

                ret = MeasureStation.Instance.VisionResult_Laser_Up(VisName3, "UpLaserData", ref listDataItem3, lmage上激光, PanNub, "1");

                ret = Transform.Instance.VisionResult_Laser(VisName4, "DownLaserData", ref listDataItem4, "DownLaser", lmage下激光,
                                        PanNub, "1");//ID.ToString()


                Data_相机工站_载具1.MeasureData.AddRange(listDataItem1);
                Data_相机工站_载具1.MeasureData.AddRange(listDataItem2);
                Data_相机工站_载具1.MeasureData.AddRange(listDataItem3);
                Data_相机工站_载具1.MeasureData.AddRange(listDataItem4);
                if (PanNub == 0)
                {
                    Data_相机工站_载具1.Position = "0";
                }
                else if (PanNub == 1)
                {
                    Data_相机工站_载具1.Position = "1";
                }
                JUDGEMENT_RESULT result = Jugement.JugeMeasureData(ref Data_相机工站_载具1);
                Data_相机工站_载具1.MeasureData.Sort(SortMeasureSize);//按照ID排序

                PublicMethod.SaveCsv(Data_相机工站_载具1, FileName[FileName.Length - 1]);
            }
        }

        private static int SortMeasureSize(DataItem x, DataItem y)
        {
            if (x.ID > y.ID)
                return 1;
            if (x.ID < y.ID)
                return -1;
            return 0;
        }

        private void button26_Click(object sender, EventArgs e)
        {
            try
            {
                ScanReader2.ReaderIP = "192.168.100.222";
                bool rtn = Common.ScanReader2.ConnectReader();
                if (!rtn)
                {
                    MessageBox.Show("初始化失败！");
                }
                else { MessageBox.Show("初始化失败！"); }
            }
            catch (Exception ex)
            {
                Frm_InitItemStatu.Instance.UpdateStep(97, Configuration.language == Language.English ? "ScanReader" : "右侧扫码枪连接异常", false);
            }

            try
            {
                ScanReader1.ReaderIP = "192.168.100.111";
                bool rtn = Common.ScanReader1.ConnectReader();

                if (!rtn)
                {
                    MessageBox.Show("初始化失败！"); ;
                }
                else { MessageBox.Show("初始化失败！"); }
            }
            catch (Exception ex)
            {
                Frm_InitItemStatu.Instance.UpdateStep(97, Configuration.language == Language.English ? "ScanReader" : "左侧扫码枪连接异常", false);
            }
        }

        private void button27_Click(object sender, EventArgs e)
        {
            textBox3.Text = ScanReader1.TrigReader(2000);
        }

        private void button28_Click(object sender, EventArgs e)
        {
            textBox4.Text = ScanReader2.TrigReader(2000);
        }

        private void button29_Click(object sender, EventArgs e)
        {

        }

        private void button30_Click(object sender, EventArgs e)
        {
            if (pointCheckEnd == true && Cur点检次数 >= 1)
            {
                if (PublicMethod.AlarmPause("提示", $"点检1次已完成", "点检1次完成，是否再次点检", "再次点检", "取消") == DialogResult.OK)
                {
                    pointCheckEnd = false;
                    Cur点检次数 = 0;
                }
                else
                {
                    return;
                }
            }
            点检启动一次 = true;
            //Common.pointCheck = true;
            治具1点检 = true;
            whichBlock = 2;
        }

        private void button31_Click(object sender, EventArgs e)
        {
            if (pointCheckEnd == true && Cur点检次数 >= 1)
            {
                if (PublicMethod.AlarmPause("提示", $"点检1次已完成", "点检1次完成，是否再次点检", "再次点检", "取消") == DialogResult.OK)
                {
                    pointCheckEnd = false;
                    Cur点检次数 = 0;
                }
                else
                {
                    return;
                }
            }
            点检启动一次 = true;
            //Common.pointCheck = true;
            治具1点检 = true;
            whichBlock = 1;
        }

        private void button32_Click(object sender, EventArgs e)
        {
            if (pointCheckEnd == true && Cur点检次数 >= 1)
            {
                if (PublicMethod.AlarmPause("提示", $"点检1次已完成", "点检1次完成，是否再次点检", "再次点检", "取消") == DialogResult.OK)
                {
                    pointCheckEnd = false;
                    Cur点检次数 = 0;
                }
                else
                {
                    return;
                }
            }
            点检启动一次 = true;
            //Common.pointCheck = true;
            治具1点检 = true;
            whichBlock = 0;
        }

        private void button33_Click(object sender, EventArgs e)
        {
            if (pointCheckEnd == true && Cur点检次数 >= 1)
            {
                if (PublicMethod.AlarmPause("提示", $"点检1次已完成", "点检1次完成，是否再次点检", "再次点检", "取消") == DialogResult.OK)
                {
                    pointCheckEnd = false;
                    Cur点检次数 = 0;
                }
                else
                {
                    return;
                }
            }
            点检启动一次 = true;
            //Common.pointCheck = true;
            治具2点检 = true;
            whichBlock = 2;
        }

        private void button34_Click(object sender, EventArgs e)
        {
            if (pointCheckEnd == true && Cur点检次数 >= 1)
            {
                if (PublicMethod.AlarmPause("提示", $"点检1次已完成", "点检1次完成，是否再次点检", "再次点检", "取消") == DialogResult.OK)
                {
                    pointCheckEnd = false;
                    Cur点检次数 = 0;
                }
                else
                {
                    return;
                }
            }
            点检启动一次 = true;
            //Common.pointCheck = true;
            治具2点检 = true;
            whichBlock = 1;
        }

        private void button35_Click(object sender, EventArgs e)
        {
            if (pointCheckEnd == true && Cur点检次数 >= 1)
            {
                if (PublicMethod.AlarmPause("提示", $"点检1次已完成", "点检1次完成，是否再次点检", "再次点检", "取消") == DialogResult.OK)
                {
                    pointCheckEnd = false;
                    Cur点检次数 = 0;
                }
                else
                {
                    return;
                }
            }
            点检启动一次 = true;
            //Common.pointCheck = true;
            治具2点检 = true;
            whichBlock = 0;
        }


    }
    #endregion

    public delegate void ChangeProjectDelegate(string currentProjectName);
}
